//
//  CWDataBase.m
//  CWDevelop
//
//  Created by LittoCats on 7/24/14.
//  Copyright (c) 2014 Littocats. All rights reserved.
//

#import "CWDataBase.h"

@interface CWDataBase ()

@property (nonatomic, strong) CBLManager *dbManager;

@end

@implementation CWDataBase

#pragma mark-
+ (CBLManager *)manager
{
    static CBLManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSError* error;
        CBLManagerOptions options;
        options.readOnly = NO;
        manager = [[CBLManager alloc] initWithDirectory: [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] options: &options error: &error ];
        if (error) {
            NSLog(@"Cannot create Manager instance with custom options");
            manager = nil;
        }
    });
    return manager;
}

+ (CBLDatabase *)dataBase:(NSString *)dbName
{
    NSString *databaseName = [[[NSString stringWithFormat:@"%@%@%@",[[NSBundle mainBundle] bundleIdentifier],dbName ? @"." : @"", dbName ? dbName : @""] lowercaseString] stringByReplacingOccurrencesOfString:@"." withString:@"--"];
    NSError *error;
    CBLDatabase *dataBase = [[self manager] databaseNamed:databaseName error:&error];
    NSAssert(!error, @"Cannot open dataBase named %@ , error < %@ >",dbName,error);
    
    return dataBase;
}
@end
